package com.huatai.bi.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.huatai.common.error.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class PythonCodeUtil {

    private final static String SEPARATOR = File.separator;

	public static JSONArray exec(String execCommand, String code, String path, Long id){
		String fileName = path+SEPARATOR+id+".py";
		try {
			//python脚本文件保存到文件中执行
			File filePath = new File(path);
			if(!filePath.exists()){
				filePath.mkdirs();
			}
			byte[] arr = code.getBytes();
			Files.write(Paths.get(fileName),arr, StandardOpenOption.CREATE);

			String[] command = new String[] {execCommand,fileName};
			final Process process = Runtime.getRuntime().exec(command);

			//正常
			String str = printMessage(process.getInputStream());
			//异常
			String errorMsg = printMessage(process.getErrorStream());
			if(StringUtils.isNoneBlank(errorMsg)){
				throw new ServiceException("脚本执行异常，异常信息："+errorMsg);
			}
			return JSONArray.parseArray(str);
		}catch (JSONException e){
			throw new ServiceException("返回数据异常,返回数据不是json格式");
		}catch (Exception e){
			throw new ServiceException("异常信息："+e.getMessage());
		}finally {
			try {
				Files.deleteIfExists(Paths.get(fileName));
			}catch (Exception e){}
		}
	}

    private static String printMessage(final InputStream input){
        Reader reader = null;
        BufferedReader bf = null;
        StringBuffer buffer = new StringBuffer();
        try {
            reader = new InputStreamReader(input);
            bf = new BufferedReader(reader);
            String line = null;
            //读最后一次数据
            while((line=bf.readLine())!=null) {
                buffer.append(line);
                buffer.append("\n");
            }
            reader.close();
            bf.close();
        } catch (IOException e) {
            throw new ServiceException("读取数据异常，异常信息："+e.getMessage());
        }finally {
            try {
                if(null != reader){
                    reader.close();
                }
                if(null != bf){
                    bf.close();
                }
            }catch (Exception e){}
        }
        return buffer.toString();
    }
}
